<script>
export default {
  name: "pager",
  props: {
    // 当前页码
    current: {
      type: Number,
      default: 1
    },
    // 总数据量
    total: {
      type: Number,
      default: 0
    },
    // 页容量
    limit: {
      type: Number,
      default: 10
    },
    //可见页码数
    visibleNumber: {
      type: Number,
      default: 10
    }
  },
  computed: {
    pageCount() {
      return Math.ceil(this.total / this.limit);
    },
    pageNumber() {
      let min, max;
      min = this.current - Math.floor(this.visibleNumber / 2)
      if (min < 1) {
        min = 1
      }
      max = min + this.visibleNumber
      if (max > this.pageCount) {
        max = this.pageCount
        min = max - this.visibleNumber
        if (min < 1) {
          min = 1
        }
      }
      return {
        min,
        max
      };
    },
    pagerNumArr() {
      let arr = []
      for (let i = this.pageNumber.min; i <= this.pageNumber.max; i++) {
        arr.push(i)
      }
      return arr
    },
  },
  methods: {
    handlePageChange(val) {
      this.$emit("pageChange", val);
    }
  }
}
</script>



<template>
  <div class="pager-container" v-if="pageCount > 1">
    <!-- 首页、上一页 -->
    <a @click="handlePageChange(1)" :class="{ disable: current === 1 }">|&lt;&lt;</a>
    <a @click="handlePageChange(current - 1)" :class="{ disable: current === 1 }">&lt;&lt;</a>

    <!-- 页码部分 -->
    <a v-for="i in pagerNumArr" :key="i" @click="handlePageChange(i)" :class="{ active: i === current }">{{ i }}</a>

    <!-- 尾页、下一页 -->
    <a @click="handlePageChange(current + 1)" :class="{ disable: current === pageCount }">&gt;&gt;</a>
    <a @click="handlePageChange(pageCount)" :class="{ disable: current === pageCount }">&gt;&gt;|</a>
  </div>
</template>



<style lang='less' scoped>
@import '../../styles/var.less';

.pager-container {
  display: flex;
  justify-content: center;

  a {
    padding: 5px;
    margin-right: 10px;
    color: @primary;
    cursor: pointer;

    &.active {
      color: @success;
      cursor: auto;
    }

    &.disable {
      color: @lightWords;
      cursor: not-allowed;
    }
  }
}
</style>